﻿using JNPF.Basics.Logic;
using JNPF.Basics.Models;
using JNPF.Basics.Models.Permission.Dtos.Position;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Controller
{
    /// <summary>
    /// 岗位管理
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.09.21
    /// </summary>
    [Route("api/Permission/[controller]")]
    public class PositionController : BaseApiController
    {
        private PositionBll positionBll = new PositionBll();
        private OrganizeBll organizeBll = new OrganizeBll();
        private DictionaryDataBll dictionaryDataBll = new DictionaryDataBll();

        #region GET
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(PositionListQuery input)
        {
            var pageInput = input.MapTo<PageInput>();
            if (!input.organizeId.IsNullOrEmpty())
            {
                var organizeIds = await GetSubOrganizeIds(input.organizeId);
                pageInput.queryJson = new { organizeId = string.Join(",", organizeIds.ToArray()) }.ToJson();
            }
            var data = await positionBll.GetList(pageInput);
            var output = new PageResult<PositionListOutput>
            {
                list = await DataToOutput(data.list),
                pagination = data.pagination
            };
            return Success(output);
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("All")]
        public async Task<ResponseResult> GetList()
        {
            var data = (await positionBll.GetList()).FindAll(t => t.EnabledMark.Equals(1));
            var output = data.MapToList<PositionListOutput>();
            return Success(new { list = output });
        }

        /// <summary>
        /// 获取下拉框（公司+部门+岗位）
        /// </summary>
        /// <returns></returns>
        [HttpGet("Selector")]
        public async Task<ResponseResult> GetSelector()
        {
            var organizeList = (await organizeBll.GetList()).FindAll(t => t.EnabledMark.Equals(1));
            var positionList = (await positionBll.GetList()).FindAll(t => t.EnabledMark.Equals(1));
            var treeList = new List<PositionSelectorOutput>();
            organizeList.ForEach(item =>
            {
                var icon = "";
                if ("department".Equals(item.Category))
                {
                    icon = "icon-ym icon-ym-tree-department1";
                }
                else
                {
                    icon = "icon-ym icon-ym-tree-organization3";
                }
                treeList.Add(
                    new PositionSelectorOutput
                    {
                        id = item.Id,
                        parentId = item.ParentId,
                        fullName = item.FullName,
                        enabledMark = item.EnabledMark,
                        icon = icon,
                        type = item.Category,
                        sortCode = item.SortCode
                    });
            });
            positionList.ForEach(item =>
            {
                treeList.Add(
                    new PositionSelectorOutput
                    {
                        id = item.Id,
                        parentId = item.OrganizeId,
                        fullName = item.FullName,
                        enabledMark = item.EnabledMark,
                        icon = "icon-ym icon-ym-tree-position1",
                        type = "position",
                        sortCode = item.SortCode
                    });
            });
            return Success(new { list = treeList.ToTree("-1") });
        }

        /// <summary>
        /// 获取信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var entity = await positionBll.GetInfo(id);
            var output = entity.MapTo<PositionInfoOutput>();
            return Success(output);
        }
        #endregion

        #region POST
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] PositionCrInput input)
        {
            if (await positionBll.IsExistByEnCode(input.enCode, null))
            {
                return Error("编码已存在");
            }
            var entity = input.MapTo<PositionEntity>();
            var isOk = await positionBll.Create(entity);
            return isOk > 0 ? Success("新建成功") : Error("新建失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete(string id)
        {
            var entity = await positionBll.GetInfo(id);
            if (entity != null)
            {
                await positionBll.Delete(entity);
            }
            return Success("删除成功");
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update(string id, [FromBody] PositionUpInput input)
        {
            if (await positionBll.IsExistByEnCode(input.enCode, id))
            {
                return Error("编码已存在");
            }
            var entity = input.MapTo<PositionEntity>();
            var isOk = await positionBll.Update(id, entity);
            return isOk > 0 ? Success("更新成功") : Error("更新失败");
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpPut("{id}/Actions/State")]
        public async Task<ResponseResult> UpdateState(string id)
        {
            var entity = await positionBll.GetInfo(id);
            entity.EnabledMark = entity.EnabledMark == 1 ? 0 : 1;
            var isOk = await positionBll.Update(id, entity);
            return isOk > 0 ? Success("更新成功") : Error("更新失败");
        }
        #endregion

        #region Method
        /// <summary>
        /// 实体转出参数据处理（部门和类型）
        /// </summary>
        /// <param name="positionEntities"></param>
        /// <returns></returns>
        private async Task<List<PositionListOutput>> DataToOutput(List<PositionEntity> positionEntities)
        {
            var listPositionListOutput = positionEntities.Select(x => new PositionListOutput
            {
                id = x.Id,
                creatorTime = x.CreatorTime,
                department = organizeBll.GetName(x.OrganizeId),
                description = x.Description,
                type = dictionaryDataBll.GetList("dae93f2fd7cd4df999d32f8750fa6a1e").Result.Find(m => m.EnCode.Equals(x.Type)).FullName,
                enabledMark = x.EnabledMark,
                enCode = x.EnCode,
                fullName = x.FullName,
                sortCode = x.SortCode
            }).ToList();
            return listPositionListOutput;
        }

        /// <summary>
        /// 下属机构
        /// </summary>
        /// <param name="organizeId"></param>
        /// <returns></returns>
        private async Task<List<string>> GetSubOrganizeIds(string organizeId)
        {
            var data = (await organizeBll.GetList()).FindAll(x => x.EnabledMark.Equals(1));
            data = data.TreeChildNode(organizeId, t => t.Id, t => t.ParentId);
            return data.Select(m => m.Id).ToList();
        }
        #endregion
    }
}
